package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 输出与当前类Test3所在同一个包中被@AutoRunClass标注过的类的类名
 * 并且获取这些类中哪些方法被@AutoRunClass注解标注了，这个注解中的参数是什么，以及执行这些被标注了的方法
 * @author XingHaiYang
 * @date 2022/9/16 12:02
 */
public class Test3 {
    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, InstantiationException, ClassNotFoundException, URISyntaxException {
        File dir = new File(
                Test3.class.getResource(".").toURI()
        );
        File[] subs = dir.listFiles(f->f.getName().endsWith(".class"));
        for(File sub : subs){
            String fileName = sub.getName();
            String className = fileName.substring(0,fileName.indexOf("."));
            className = Test3.class.getPackage().getName()+"."+className;
            Class cls = Class.forName(className);
            if(cls.isAnnotationPresent(AutoRunClass.class)){
                System.out.println(cls.getName()+"被@AutoRunClass标注了");
                //实例化
                Object obj = cls.newInstance();

                //输出该类中所有被@AutoRunMethod标注的方法
                Method[] methods = cls.getDeclaredMethods();
                for(Method method : methods){
                    if(method.isAnnotationPresent(AutoRunMethod.class)){
                        System.out.println(method.getName()+"()被注解@AutoRunMethod标注了");
                        AutoRunMethod arm = method.getAnnotation(AutoRunMethod.class);
                        int value = arm.value();
                        for(int i=0;i<value;i++) {
                            method.invoke(obj);
                        }
                    }
                }

            }
        }
    }
}
